package com.bwie.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:${涛}
 * @Date:2024/9/3 09:00
 * @Description: UserController
 * @Version 1.0.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /*
    根据手机发送验证码
     */
    @PostMapping("/code/{phone}")
    public R code(@PathVariable(name = "phone") String phone) {
        String code = RandomUtil.randomNumbers(4);
        //1 登录页面，完成验证码发送
        Boolean aBoolean = MobileMessageUtil.sendMobileMessage(phone, code);
        stringRedisTemplate.opsForValue().set("code:" + phone, code, 5, TimeUnit.MINUTES);
        if (aBoolean) {
            return R.OK(code);
        } else {
            return R.ERROR(404, "验证码发送失败");
        }
    }


    /*

   账号 密码 验证

     */
    @PostMapping("/login")
    public R login(@RequestBody User user) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());

        User oneUser = userService.getOne(wrapper);

        if (oneUser == null) {
            return R.ERROR(404, "账号错误");
        }


        //加密密码
        String encrypt = MD5Utils.encrypt(user.getPassword());
        System.out.println("------加密密码-----" + encrypt);
        //加密判断
        if (!oneUser.getPassword().equals(encrypt)) {
            return R.ERROR(404, "密码错误");
        }


        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("id", oneUser.getId()).claim("roleId", oneUser.getRoleId()).compact();
        stringRedisTemplate.opsForValue().set("token:" + oneUser.getId(), token, 10, TimeUnit.MINUTES);


        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("roleId", oneUser.getRoleId());
        hashMap.put("token", token);
        return R.OK(hashMap);
    }

    //通过手机号获取验证码

    //然后判断是否正确
    @PostMapping("/judgment")
    public R judgment(@RequestBody User user) {


        if (StringUtils.isEmpty(user.getPhone())) {
            return R.ERROR(404, "手机号不能为空");
        }
        if (StringUtils.isEmpty(user.getCode())) {
            return R.ERROR(404, "验证码不能为空");
        }


        String code = stringRedisTemplate.opsForValue().get("code:" + user.getPhone());

        if (StringUtils.isEmpty(code)) {
            return R.ERROR(404, "验证为空");
        }

        Long expire = stringRedisTemplate.getExpire("code:" + user.getPhone(), TimeUnit.MINUTES);

        //2.2 redis验证过期、不到3分钟给出提示信息。
        if (expire < 3) {
            return R.ERROR(404, "~~~~~~~~~验证码快要过期了~~~~~~~");
        }

        if (!code.equals(user.getCode())) {
            return R.ERROR(404, "验证码错误");
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        User oneUser = userService.getOne(wrapper);

        if (oneUser == null) {
            return R.ERROR(404, "手机号不存在");
        }

        return R.OK();
    }

    @PostMapping("/update")
    public R update(@RequestBody User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        User oneUser = userService.getOne(wrapper);

        if (oneUser == null) {
            return R.ERROR(404, "手机号不存在");
        }

        oneUser.setPassword(user.getPassword());

        userService.updateById(oneUser);
        return R.OK();
    }
}


